import compose from './compose'

const applyMiddleware = function(...middlewares) {
  /* 返回一个重写createStore的方法 */
  return function rewriteCreateStoreFunc(oldCreateStore) {
    return function newCreateStore(reducer, initState) {
      /* 修改完正store, 最小开放策略 simpleStore  */
      const store = oldCreateStore(reducer, initState) 
      const simpleStore = { getState: store.getState } 

      const chain = middlewares.map(middlewares => middlewares(simpleStore))

      // let dispatch = store.dispatch
      // /* 实现 exception(time((logger(dispatch))))*/
      // chain.reverse().map(middlewares => {
      //   dispatch = middlewares(dispatch)
      // })

      /* 重写 dispatch */
      // store.dispatch = dispatch
      // return store

      const dispatch = compose(...chain)(store.dispatch)

      return {
        ...store,
        dispatch
      }
    }
  }
}

export default applyMiddleware;